package com.xjl.example.aqs;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by xiaojinlu1990@163.com on 2019/11/30.
 * countDownLatch 的三个重要的方法 （适用场景：用于并行计算）
 * 1 只有一个线程可调用
 * 2 当初始化的值减为一时才会去执行对应的操作
 * 3 可添加执行超时时间
 *
 */
public class CountDownLatchExmaple {

    private static Logger log = LoggerFactory.getLogger(CountDownLatch.class);

    public final static int clienttotal = 500;
    public final static int threadTotal = 200;
    public static int count = 0;


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newCachedThreadPool();
        final CountDownLatch downLatch = new CountDownLatch(clienttotal);

        for (int i = 0; i < clienttotal; i++) {
            executor.execute(() ->{
                try {
                    add();
                }catch (Exception e){
                    log.info("{}",e.getStackTrace());
                }finally {
                    downLatch.countDown();
                }
            });
        }
        downLatch.await(10, TimeUnit.MILLISECONDS);
        log.info("finish!!!");
        executor.shutdown();
    }

    private static void add() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
        log.info("{}",count);
    }


}
